<?php

namespace app\newapi\controller;

use think\Request;
use think\Session;
use think\Controller;
use app\common\model\WxUser as WxUserModel;
use app\common\model\Pushmessage as PushmessageModel;
use app\common\model\AuthorWxUser;
use app\common\model\Users as UsersModel;
use app\common\util\WechatThirdUtil;
use htq\HTQClient; //队列类
use think\Db;

class Template extends Controller
{
    protected $config;
    protected $wechat_obj;
    protected $third_config;
    protected $wx_user_model;
    protected $author_wx_user;
    protected $pushmessage_model;
    protected $HTQClient;
    protected $users_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->wx_user_model = new WxUserModel();
        $this->author_wx_user = new AuthorWxUser();
        $this->pushmessage_model = new PushmessageModel();
        $this->users_model = new UsersModel();
        // $this->config = $this->author_wx_user->where('id',1)->find(); //当前授权公众号信息(小微转头条测试)
        $this->third_config = $this->wx_user_model->find(); //第三方开发平台信息

        $this->HTQClient = new HTQClient('J6E04AifABuDRfsMm2Qt4WMJHq201vmz', 'Hc9KVU6cGDWxoQ7PjSxwYQOLrCcg6wFj');
    }

    /*
     * 新增模板消息测试接口
     * 获取可以发送的模板消息列表
     * */
    public function getTemplateList($auid=0)
    {
        $where = [  'uid'=>['eq',1],   'id' => ['eq',$auid],   ];
        $wechat_info = Db::name('author_wx_user')->where($where)->find();
        if($auid){
            $this->wechat_obj = new WechatThirdUtil($this->third_config , $wechat_info);
//        1 获取模板列表
            $template_list = $this->wechat_obj->getTemplateList();
            return json($template_list);
        }else{
            return json(['error'=>404,'msg'=>'公众号不存在']);
        }
    }

    /*
     * 模板消息的发送
     * */
    public function sendTemplateMsg($auid)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $template_msg = $data['data'];
            // $send_openids = $template_msg['openid'];
            $where = [
                'auid' => ['eq', $auid],
                'subscribe' => ['eq', 1],
            ];
            $send_openids = $this->users_model->where($where)->column('openid');
            if (empty($send_openids)) {
                $this->HTQClient->deleteQueue($template_msg['queue_name']); //openids不是数组直接删除队列
                return;
            }
            $this->config = $this->author_wx_user->where('id', $auid)->find();
            $this->wechat_obj = new WechatThirdUtil($this->third_config, $this->config);

            foreach ($send_openids as $openid) {
                $template_msg['data']['touser'] = $openid;
                $result = $this->wechat_obj->sendTemplateMsg($template_msg['data']);
                if (!$result) {
                    //如果发生错误会提醒管理员
                    // echo json(['status' => -1 ,'error' => 'send template error']);
                    echo $openid;
                }
            }
            //队列全部执行完并提醒管理员 return只是暂时的 删除队列
            $return = $this->HTQClient->deleteQueue($template_msg['queue_name']);
            if ($return['error_code'] == 1004) {
                //删除失败
                $arr_data = [
                    'type' => 'push_message',
                    'data' => [
                        'uid' => $this->config['uid'],
                        'status' => -1,
                        'title' => '模板消息',
                        'message' => '公众号 '.$this->config['wxname'].' 模板消息队列删除失败,需联系管理员',
                    ],
                ];
            } else {
                $arr_data = [
                    'type' => 'push_message',
                    'data' => [
                        'uid' => $this->config['uid'],
                        'status' => 1,
                        'title' => '模板消息',
                        'message' => '公众号 '.$this->config['wxname'].' 模板消息以全部发送成功!',
                    ],
                ];
            }

            // sendWebSocket($arr_data);
            $this->pushmessage_model->allowField(true)->save($arr_data['data']);

            return json(['status' => 1, 'msg' => 'ok']);
        } else {
            return json(['status' => -1, 'error' => 'post method error']);
        }
    }

    /*
     * 修改版, 除去武汉和广东的用户
     * */
    public function sendTemplateMsgWithoutWG($auid)
    {
        $citys = ['武汉'];
        $province= ['广东'];
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $template_msg = $data['data'];
            // $send_openids = $template_msg['openid'];
            $where = [
                'auid' => ['eq', $auid],
                'subscribe' => ['eq', 1],
            ];
            //             $send_openids = $this->users_model->where($where)->column('openid');
            $send_openids = $this->users_model->where($where)->whereNotIn('city',$citys)->whereNotIn('province',$province)->column('openid');
            if (empty($send_openids)) {
                $this->HTQClient->deleteQueue($template_msg['queue_name']); //openids不是数组直接删除队列
                return;
            }
            $this->config = $this->author_wx_user->where('id', $auid)->find();
            $this->wechat_obj = new WechatThirdUtil($this->third_config, $this->config);

            foreach ($send_openids as $openid) {
                $template_msg['data']['touser'] = $openid;
                $result = $this->wechat_obj->sendTemplateMsg($template_msg['data']);
                if (!$result) {
                    //如果发生错误会提醒管理员
                    // echo json(['status' => -1 ,'error' => 'send template error']);
                    echo $openid;
                }
            }
            //队列全部执行完并提醒管理员 return只是暂时的 删除队列
            $return = $this->HTQClient->deleteQueue($template_msg['queue_name']);
            if ($return['error_code'] == 1004) {
                //删除失败
                $arr_data = [
                    'type' => 'push_message',
                    'data' => [
                        'uid' => $this->config['uid'],
                        'status' => -1,
                        'title' => '模板消息',
                        'message' => '公众号 '.$this->config['wxname'].' 模板消息队列删除失败,需联系管理员',
                    ],
                ];
            } else {
                $arr_data = [
                    'type' => 'push_message',
                    'data' => [
                        'uid' => $this->config['uid'],
                        'status' => 1,
                        'title' => '模板消息',
                        'message' => '公众号 '.$this->config['wxname'].' 模板消息以全部发送成功!',
                    ],
                ];
            }

            // sendWebSocket($arr_data);
            $this->pushmessage_model->allowField(true)->save($arr_data['data']);

            return json(['status' => 1, 'msg' => 'ok']);
        } else {
            return json(['status' => -1, 'error' => 'post method error']);
        }
    }

    /*
     * 修改版, 只发给一个城市的用户
     * */
    public function sendTemplateMsgCity($auid,$city='')
    {
        if(empty($city)){
            $citys = ['中西区'];  // 西贡区  中西区
        }
        //         $province= ['广东'];
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $template_msg = $data['data'];
            // $send_openids = $template_msg['openid'];
            $where = [
                'auid' => ['eq', $auid],
                'subscribe' => ['eq', 1],
            ];
            //             $send_openids = $this->users_model->where($where)->column('openid');
            // ->whereNotIn('city',$citys)->whereNotIn('province',$province)
            $send_openids = $this->users_model->where($where)->whereIn('city',$citys)->column('openid');
            if (empty($send_openids)) {
                $this->HTQClient->deleteQueue($template_msg['queue_name']); //openids不是数组直接删除队列
                return;
            }
            $this->config = $this->author_wx_user->where('id', $auid)->find();
            $this->wechat_obj = new WechatThirdUtil($this->third_config, $this->config);

            foreach ($send_openids as $openid) {
                $template_msg['data']['touser'] = $openid;
                $result = $this->wechat_obj->sendTemplateMsg($template_msg['data']);
                if (!$result) {
                    //如果发生错误会提醒管理员
                    // echo json(['status' => -1 ,'error' => 'send template error']);
                    echo $openid;
                }
            }
            //队列全部执行完并提醒管理员 return只是暂时的 删除队列
            $return = $this->HTQClient->deleteQueue($template_msg['queue_name']);
            if ($return['error_code'] == 1004) {
                //删除失败
                $arr_data = [
                    'type' => 'push_message',
                    'data' => [
                        'uid' => $this->config['uid'],
                        'status' => -1,
                        'title' => '模板消息',
                        'message' => '公众号 '.$this->config['wxname'].' 模板消息队列删除失败,需联系管理员',
                    ],
                ];
            } else {
                $arr_data = [
                    'type' => 'push_message',
                    'data' => [
                        'uid' => $this->config['uid'],
                        'status' => 1,
                        'title' => '模板消息',
                        'message' => '公众号 '.$this->config['wxname'].' 模板消息以全部发送成功!',
                    ],
                ];
            }

            // sendWebSocket($arr_data);
            $this->pushmessage_model->allowField(true)->save($arr_data['data']);

            return json(['status' => 1, 'msg' => 'ok']);
        } else {
            return json(['status' => -1, 'error' => 'post method error']);
        }
    }


    public function queue()
    {
        $template_msg = $this->request->post();
        //队列名称
        $queue_name = 'queue_'.date('Ymd').'_'.session::get('admin_id').date('His').rand(1, 9999);
        $template_msg['queue_name'] = $queue_name;
        $str = base64_encode(json_encode($template_msg));
        $url = QUEUE_URL.'/api/Template/sendTemplateMsg';
        $ret = $this->HTQClient->addQueue($queue_name, 'real_time');
        if ($ret['error_code'] == 1002) {
            //队列已存在请重新操作
            return false;
        }
        $result = $this->actioning_queue($queue_name, $url);
        if ($result['error_code'] == 0) {
            //队列任务添加成功
            dump($result);

            return '队列任务添加成功';
        } elseif ($result['error_code'] == 1001) {
            //队列任务添加失败
            return false;
        }
    }

    public function queueAll()
    {
        $ret = $this->HTQClient->allQueue();
        dump($ret);
    }

    public function getQueueAll()
    {
        $ret = $this->HTQClient->allQueue();

        return $ret;
    }

    public function del()
    {
        $queueall = $this->getQueueAll();
        foreach ($queueall as $v) {
            $ret = $this->HTQClient->deleteQueue($v['queue_name']);
            var_dump($ret);
        }
    }

    public function count()
    {
        $queueall = $this->getQueueAll();
        foreach ($queueall as $v) {
            $ret = $this->HTQClient->countQueue($v['queue_name']);
            var_dump($ret);
        }
    }

    public function actioning_queue($queue_name, $url)
    {
        $ret = $this->HTQClient->addTask($queue_name, $url);

        return $ret;
    }

    // ----------------  发送单条模板消息



    public function checkData($templateData=''){
        $data = [];
        $templateData2 = '{
           "touser":"olDrH0tNRPEOlWXwx3lEzb-Tb_UM",
           "template_id":"iSSQFdqmxUDfnQ6dpX2sm9o47Xy2a_uDwxU_2eq1X2U",
           "url":"https://www.baidu.com/",
           "data":{
                   "first": {
                       "value":"恭喜你购买成功！",
                       "color":"#173177"
                   },
                   "activity_name":{
                       "value":"活动名称",
                       "color":"#173177"
                   },
                   "reserve_results": {
                       "value":"预约结果",
                       "color":"#173177"
                   },
                   "activity_time": {
                       "value":"活动时间",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"欢迎再次购买！",
                       "color":"#173177"
                   }
           }
       }';
//        var_dump($templateData);
//        echo '-----------';
//        $data['data0'] = json_encode($templateData);

//        $data['data1'] = json_decode($templateData, true);

//        var_dump($templateData);
//        echo '-------------';
        $data['data2'] = json_decode($templateData2, true);
//        var_dump($templateData2);
        return json(['first'=>$templateData,'data'=>$data]);

//        $this->config = $this->author_wx_user->where('id', 111)->find();
//        $this->wechat_obj = new WechatThirdUtil($this->third_config, $this->config);
//        $data['data'] = json_decode($templateData, true);
//        $result = $this->wechat_obj->sendTemplateMsg($data['data']);
//        return json($result);
    }

    public function sendOne($templateData=''){
        $data = [];
        if(empty($templateData)) {
            $templateData = '{"touser":"olDrH0tNRPEOlWXwx3lEzb-Tb_UM",
           "template_id":"iSSQFdqmxUDfnQ6dpX2sm9o47Xy2a_uDwxU_2eq1X2U",
           "url":"https://www.baidu.com/",
           "data":{"first": {"value":"恭喜你购买成功！","color":"#173177"},
                   "activity_name":{"value":"活动名称","color":"#173177"},
                   "reserve_results": {"value":"预约结果","color":"#173177"},
                   "activity_time": {"value":"活动时间","color":"#173177"},
                   "remark":{"value":"欢迎再次购买！","color":"#173177"}}}';
            $data['data'] = json_decode($templateData, true);
        }else{
            $data['data'] = $templateData;
        }
        $this->config = $this->author_wx_user->where('id', 111)->find();
        $this->wechat_obj = new WechatThirdUtil($this->third_config, $this->config);
        $result = $this->wechat_obj->sendTemplateMsg($data['data']);
        return json($result);
    }

    // 微信封域名通知  '.$pid.'
    public function sendOneWX($first,$remark,$pid=0){
        // 优先发给客户
        $this->config = $this->author_wx_user->where('id', 111)->find();
        $this->wechat_obj = new WechatThirdUtil($this->third_config, $this->config);

        if($pid){
            $map = ['type' => 1, 'pid'  => $pid];
            $notice = Db::name('wxurlnotice')->where($map)->column('notice');
            $notic_url = 'https://tongji.fulanyu.cn/index/wechat/hc/pid/'.$pid;
            foreach($notice as $notic ){
                $data = [];
                $templateData = '{"touser":"'.$notic.'",
           "template_id":"iSSQFdqmxUDfnQ6dpX2sm9o47Xy2a_uDwxU_2eq1X2U",
           "url":"'.$notic_url.'",
           "data":{"first": {"value":"'.$first.'","color":"#ff0000"},
                   "activity_name":{"value":"微信检查","color":"#00ff00"},
                   "reserve_results": {"value":"保证正常接收消息","color":"#173177"},
                   "activity_time": {"value":"活动时间","color":"#173177"},
                   "remark":{"value":"'.$remark.'","color":"#0000ff"}}}';
                $data['data'] = json_decode($templateData, true);
                $this->wechat_obj->sendTemplateMsg($data['data']);
            }
        }

        $map = [ 'type' => 1, 'pid'  => 0];
        $notice = Db::name('wxurlnotice')->where($map)->column('notice');
        foreach($notice as $notic ){
            $data = [];
            $templateData = '{"touser":"'.$notic.'",
           "template_id":"iSSQFdqmxUDfnQ6dpX2sm9o47Xy2a_uDwxU_2eq1X2U",
           "url":"https://tongji.fulanyu.cn/index/wechat/hc/pid/",
           "data":{"first": {"value":"'.$first.'","color":"#ff0000"},
                   "activity_name":{"value":"微信检查正式启用","color":"#00ff00"},
                   "reserve_results": {"value":"保证正常接收消息","color":"#173177"},
                   "activity_time": {"value":"活动时间","color":"#173177"},
                   "remark":{"value":"'.$remark.'","color":"#0000ff"}}}';
            $data['data'] = json_decode($templateData, true);
            $this->wechat_obj->sendTemplateMsg($data['data']);
        }
    }
    // 版本 2.0.2
    public function sendOneWX1($first,$remark,$pid=0){
        // 优先发给客户
        $this->config = $this->author_wx_user->where('id', 111)->find();
        $this->wechat_obj = new WechatThirdUtil($this->third_config, $this->config);
        $map = [];
        if($pid){
            $map = ['type' => 1, 'pid'  => $pid];
            $notice = Db::name('wxurlnotice')->where($map)->column('notice');
            foreach($notice as $notic ){
                $data = [];
                $templateData = '{"touser":"'.$notic.'",
           "template_id":"iSSQFdqmxUDfnQ6dpX2sm9o47Xy2a_uDwxU_2eq1X2U",
           "url":"https://haicaochat.com/",
           "data":{"first": {"value":"'.$first.'","color":"#ff0000"},
                   "activity_name":{"value":"微信检查","color":"#00ff00"},
                   "reserve_results": {"value":"保证正常接收消息","color":"#173177"},
                   "activity_time": {"value":"活动时间","color":"#173177"},
                   "remark":{"value":"'.$remark.'","color":"#0000ff"}}}';
                $data['data'] = json_decode($templateData, true);
                $this->wechat_obj->sendTemplateMsg($data['data']);
            }
        }

        $map = [ 'type' => 1, 'pid'  => 0];
        $notice = Db::name('wxurlnotice')->where($map)->column('notice');
        foreach($notice as $notic ){
            $data = [];
            $templateData = '{"touser":"'.$notic.'",
           "template_id":"iSSQFdqmxUDfnQ6dpX2sm9o47Xy2a_uDwxU_2eq1X2U",
           "url":"https://haicaochat.com/",
           "data":{"first": {"value":"'.$first.'","color":"#ff0000"},
                   "activity_name":{"value":"微信检查临时测试,非常规","color":"#00ff00"},
                   "reserve_results": {"value":"保证正常接收消息","color":"#173177"},
                   "activity_time": {"value":"活动时间","color":"#173177"},
                   "remark":{"value":"'.$remark.'","color":"#0000ff"}}}';
            $data['data'] = json_decode($templateData, true);
            $this->wechat_obj->sendTemplateMsg($data['data']);
        }
    }

    // -----------------



    public function test3()
    {
        $data = $this->request->post();
        $template_msg = $data['data'];
        $send_openids = $template_msg['openid'];
        foreach ($send_openids as $openid) {
            file_put_contents('./abc.log', $openid, FILE_APPEND);
            $template_msg['data']['touser'] = $openid;
            $result = $this->wechat_obj->sendTemplateMsg($template_msg['data']);
            if (!$result) {
                //如果发生错误会提醒管理员 return只是暂时的
                return json(['status' => -1, 'error' => 'send template error']);
            }
        }
        //队列全部执行完并提醒管理员 return只是暂时的 删除队列
        $return = $this->HTQClient->deleteQueue($template_msg['queue_name']);
        if ($return['error_code'] == 1004) {
            //删除失败
            return false;
        }

        return json(['status' => 1, 'mag' => 'ok']);
    }
}
